package com.flnet.treasure.service.impl;


import com.flnet.common.utils.UUIDUtils;
import com.flnet.treasure.domain.FileRef;
import com.flnet.treasure.domain.FileRefExample;
import com.flnet.treasure.mapper.FileRefMapper;
import com.flnet.treasure.service.CommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class CommonServiceImpl implements CommonService {
	/*@Value("${user.img.address}")
	private String userImgSddress;
	@Value("${nginx_url}")
	private String nginx_url;*/

	@Autowired
	private FileRefMapper fileRefMapper;

	
	@Override
	public FileRef uploadImg(MultipartFile file,String userImgSddress,String nginx_url) throws IOException {

        String path=userImgSddress;
        // 创建文件 
        File dir=new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String uuid = UUIDUtils.getUUID();
        String fileName=file.getOriginalFilename();
        String img=uuid+fileName.substring(fileName.lastIndexOf("."));//zhao.jpg
        FileOutputStream imgOut=new FileOutputStream(new File(dir,img));//根据 dir 抽象路径名和 img 路径名字符串创建一个新 File 实例。
        imgOut.write(file.getBytes());//返回一个字节数组文件的内容
        imgOut.close();
        FileRef fileRef = new FileRef();
        fileRef.setUuid(uuid);
        fileRef.setCreateDate(new Date());
       // fileRef.setCreator(ShiroUtils.getUserId());
        fileRef.setModifyDate(new Date());
      //  fileRef.setModifier(ShiroUtils.getUserId());
        fileRef.setFileName(img);
        fileRef.setType(fileName.substring(fileName.lastIndexOf("."),fileName.length()));
        fileRef.setPath(path);
        fileRef.setFileUrl(nginx_url+"/"+img);
        fileRef.setActiveFlag(1);

        int id = fileRefMapper.insertSelective(fileRef);
        FileRefExample example = new FileRefExample();

        example.createCriteria().andFileNameEqualTo(img);
		List<FileRef> list = fileRefMapper.selectByExample(example );
		return list.get(0);

	}
    
	@Override
	public List<FileRef> getFileInfo(Long fileId) {	
		List<FileRef> list=null;
		if(fileId==null) {
			list=fileRefMapper.selectByExample(new FileRefExample());
			return list;
		}
		FileRefExample fre=new FileRefExample();
		fre.createCriteria().andIdEqualTo(fileId);
		list=fileRefMapper.selectByExample(fre);
		return list;
	}

}
